package com.example.excel_import_demo.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * @author benjamin_5
 * @Description
 * @date 2024/2/19
 */
public class ExcelUtil {
    private static Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 导入数据
     * @param file
     * @param titleRows 标题在第几行
     * @param headerRows 表头在第几行
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows,
                                          Class<T> clazz) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setNeedVerify(true);
        ExcelImportResult<T> result = null;
        try {
            InputStream inputStream = file.getInputStream();
            result = ExcelImportUtil.importExcelMore(inputStream, clazz, params);
        } catch (NoSuchElementException e) {
            // 日志记录错误
            log.error(String.format("导入数据为空: %s", e));
            throw new RuntimeException("导入数据为空");
        } catch (Exception e) {
            // 日志记录错误
            e.printStackTrace();
            log.error(String.format("导入失败: %s", e));
            throw new RuntimeException("导入失败");
        }
        if (result == null) {
            return null;
        }
        if (result.isVerifyFail()) {
            // 如有需要，可以根据result.getFailWorkbook();获取到有错误的数据
            throw new RuntimeException("校验出错");
        }
        return result.getList();
    }

    public static <T> void downLoadExcel(String fileName, HttpServletResponse response,Class clazz,Workbook workbook) throws RuntimeException{
        ExportParams params = new ExportParams();
        params.setSheetName("data");//设置sheet名
        try {
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setCharacterEncoding("utf-8");
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            // 一个自定义枚举 错误信息的
            e.printStackTrace();
            throw new RuntimeException("下载出错");
        }
    }

    public static <T> void downLoadExcel(String fileName, HttpServletResponse response,Class clazz, List<T> dataList) throws RuntimeException{
        ExportParams params = new ExportParams();
        params.setSheetName("data");//设置sheet名
        Workbook workbook = ExcelExportUtil.exportExcel(params, clazz, dataList);
        downLoadExcel(fileName, response, clazz, workbook);
    }
}
